package edu.ccut.saturn.manager.bundles.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IBundleComponentInfo;
import edu.ccut.saturn.component.IComponentInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDataManager;
import edu.ccut.saturn.component.impl.SaturnActionComponentInfo;
import edu.ccut.saturn.component.impl.SaturnBaseComponentInfo;
import edu.ccut.saturn.component.impl.SaturnLogicComponentInfo;

public class GetChildTree extends DefaultComponent {

	private static final String IMAGE_PATH = "component/";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		//形如 com.saturn.demo.bank
		String key = (String) parameterContext.getParameterValue(0);
		//形如 Data （文件夹）
		String parentId = (String) parameterContext.getParameterValue(1);
		//形如 /Data/
		String parentStr = "/" + parentId + "/";
		IBundleComponentInfo bundleComponentInfo = ComponentManager
				.getInstance().getBundleComponentInfo(key);

		List<String> componentStringList = new ArrayList<String>();
		String type = "";

		if (bundleComponentInfo != null) {
			Collection<IComponentInfo> IComponentInfos = bundleComponentInfo
					.getComponentInfos();

			Iterator<IComponentInfo> componentIterator = IComponentInfos
					.iterator();

			while (componentIterator.hasNext()) {
				IComponentInfo componentInfo = componentIterator.next();
				//形如 /userModule/userLogic/Account.logic
				String componentKey = componentInfo.getKey();

				if (componentInfo instanceof SaturnActionComponentInfo) {
					type = "action_saturnfolder";

				} else if (componentInfo instanceof SaturnLogicComponentInfo) {
					type = "logic_saturnfolder";

				} else if (componentInfo instanceof SaturnBaseComponentInfo) {
					type = "component_saturnfolder";

//				} else if (componentInfo instanceof SaturnDataInfo) {
//					type = "data_saturnfolder";
//
//				} else if (componentInfo instanceof SaturnValidateInfo) {
//					type = "validate_saturnfolder";
//
//				} else if (componentInfo instanceof SaturnWorkFlowInfo) {
//					type = "workflow_saturnfolder";
				}
                //有父路径的才获取
				if (componentKey.indexOf(parentStr) > -1) {
					String componentStr = componentKey.substring(componentKey
							.indexOf(parentStr)
							+ parentStr.length(), componentKey.length());

					if (componentStr.indexOf("/") > -1) {
						componentStr = componentStr.substring(0, componentStr
								.indexOf("/"));

						componentStringList.add(componentStr.replace("/", "")
								+ "," + type);

					} else {
						componentStringList.add(componentStr + ","
								+ type.substring(0, type.indexOf("_")));
					}
				}
			}

			Set<String> saturnDataNamespaceKeys = SaturnDataManager.getInstance()
					.getSaturnDataInfoNamespaceKeys();

			if (saturnDataNamespaceKeys != null) {
				Iterator<String> saturnDataNamespaceKeysIterator = saturnDataNamespaceKeys
						.iterator();

				while (saturnDataNamespaceKeysIterator.hasNext()) {
					String saturnDataNameSpaceKey = saturnDataNamespaceKeysIterator
							.next();
                    //形如 saturnManager/dictModule/data
					String saturnDataNameSpaceKeyWithoutHttp = saturnDataNameSpaceKey
							.substring(7);

					String[] keyArray = saturnDataNameSpaceKeyWithoutHttp
							.split("/");

					String bundleName = keyArray[0];

					if (key.equals(bundleName)) {
						Set<String> saturnDataTypes = SaturnDataManager
								.getInstance().getSaturnDataInfoKeys(
										saturnDataNameSpaceKey);

						Iterator<String> saturnDataTypesIterator = saturnDataTypes
								.iterator();

						while (saturnDataTypesIterator.hasNext()) {
							String name = null;
							//形如  com.saturn.demo.bank/userModule/data/EMILYBANKUSER
							name = saturnDataNameSpaceKeyWithoutHttp + "/"
									+ saturnDataTypesIterator.next();

							if (name.indexOf(parentStr) > -1) {
								//形如  data/EMILYBANKUSER
								String dataStr = name.substring(name
										.indexOf(parentStr)
										+ parentStr.length(), name.length());

								if (dataStr.indexOf("/") > -1) {
									dataStr = dataStr.substring(0, dataStr
											.indexOf("/"));

									componentStringList.add(dataStr.replace(
											"/", "")
											+ ",data_saturnfolder");

								} else {
									//
									//TODO 加个后缀 .saturnData，问题是当是.sqlData文件时不能区分
									componentStringList.add(dataStr+".saturnData"
											+ ",dataComponent");
								}
							}
						}
					}
				}
			}
			componentStringList = unique(componentStringList);
			String treeXml = getTreeXml(componentStringList, parentId);
			parameterContext.setParameter(2, treeXml);
			//parameterContext.setParameter(3, componentStringList);//输出一个list 转json用
			
			List<Map> result = new ArrayList<Map>();
			
			for(String str : componentStringList){
				String text = str.split(",")[0];
				String iconType = str.split(",")[1];
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", parentId + "/" + text);
				map.put("text", text);
				//map.put("key", "edu.ccut.saturn.manager.bundles.impl");
				//map.put("type", type );
				map.put("icon", "images/"+iconType+".gif");
				if(text.indexOf(".") > 0){
					map.put("leaf", true);	
				}
				result.add(map);
			}
			parameterContext.setParameter(3, result);//输出一个list 转json用
		}
	}

	public String getTreeXml(List<String> list, String treeId) {
		Collections.sort(list);
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer
				.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tree id=\""
						+ treeId + "\">");

		for (String nameStr : list) {
			String[] nameAndType = nameStr.split(",");
			stringBuffer.append("<item text=\"").append(nameAndType[0]).append(
					"\" id=\"").append(treeId + "/" + nameAndType[0]).append(
					"\"").append(
					" im0=\"" + IMAGE_PATH + nameAndType[1] + ".gif\" im1=\""
							+ IMAGE_PATH + nameAndType[1] + ".gif\" im2=\""
							+ IMAGE_PATH + nameAndType[1] + ".gif\"");

			if (nameAndType[0].indexOf(".") > -1) {
				stringBuffer.append(" >").append("</item>");

			} else {
				stringBuffer.append(" child=\"1\" >").append("</item>");
			}
		}
		stringBuffer.append("</tree>");
		String treeXml = stringBuffer.toString();
		return treeXml;
	}

	/**
	 * 去掉list中的重复项
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> unique(List<String> list) {
		Set set = new HashSet();
		set.addAll(list);
		List list1 = new ArrayList();
		list1.addAll(set);
		return list1;
	}
}